import { useEffect } from 'react';
import { memo, useState } from 'react';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import { LeftOutline, MessageOutline, LikeOutline, StarOutline, MoreOutline } from 'antd-mobile-icons';
import { Badge } from 'antd-mobile';
import { queryNewsDetailApi, queryNewsVisitApi, collectNewsApi, queryCollectListApi, cancelCollectApi } from '@/api';
import DetailWrapper from './styled';
import showToast from '@/utils/toast';
import { useMemo } from 'react';
import { connect } from 'react-redux';
const Detail = memo((props) => {
  const params = useParams(),
    navigate = useNavigate(),
    location = useLocation(),
    [info, setInfo] = useState({}),
    [extra, setExtra] = useState({}),
    [collectList, setCollectList] = useState([]);

  let link;
  const handleStyle = (result) => {
    let { css } = result;
    if (!Array.isArray(css)) return;
    css = css[0];
    if (!css) return;
    // 创建link元素动态加载css
    link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = css;
    document.head.appendChild(link);
  };

  const handleImage = (result) => {
    let imgPlaceHolder = document.querySelector('.img-place-holder');
    if (!imgPlaceHolder) return;
    // 创建大图
    let tempImg = new Image();
    tempImg.src = result.image;
    tempImg.onload = () => {
      imgPlaceHolder.appendChild(tempImg);
    };
    // 移除占位图
    tempImg.onerror = () => {
      let parent = imgPlaceHolder.parentNode;
      parent.parentNode.removeChild(parent);
    };
  };

  useEffect(() => {
    (async () => {
      try {
        const res = await queryNewsDetailApi(params.id);
        handleImage(res);
        handleStyle(res);
        setInfo(res);
        // 销毁组件:移除创建的样式
        return () => {
          if (link) document.head.removeChild(link);
        };
      } catch (_) {}
    })();
  }, []);

  // 获取新闻访问信息
  useEffect(() => {
    (async () => {
      if (!params.id) return;
      try {
        const res = await queryNewsVisitApi(params.id);
        setExtra(res);
      } catch (_) {}
    })();
  }, []);

  // 获取收藏列表
  useEffect(() => {
    (async () => {
      try {
        const { code, data } = await queryCollectListApi();
        if (+code !== 0) return showToast('获取收藏列表失败');
        setCollectList([...data]);
      } catch (error) {}
    })();
  }, []);

  // 依赖于收藏列表和路径参数,计算出是否收藏
  const isCollection = useMemo(() => {
    if (!collectList.length) return false;
    return collectList.some((item) => {
      return +item.news.id === +params.id;
    });
  }, [collectList, params]);

  const { userInfo } = props;
  // 收藏/取消收藏
  const setCollection = async () => {
    if (!userInfo.id) {
      navigate(`/login?to=${location.pathname}`);
      return;
    }
    // 收藏
    if (!isCollection) {
      try {
        let { code } = await collectNewsApi(params.id);
        if (+code !== 0) {
          showToast('收藏失败');
        } else {
          showToast('收藏成功');
        }
        // 重新获取收藏列表
        const res = await queryCollectListApi();
        if (+res.code !== 0) {
          showToast({ content: '获取收藏列表失败' });
        }
        setCollectList([...res.data]);
      } catch (_) {}
    }
    // 取消收藏
    if (isCollection) {
      try {
        const curNews = collectList.find((item) => +item.news.id === +params.id);
        const { code } = await cancelCollectApi(curNews.id);
        if (+code !== 0) {
          showToast('取消收藏失败');
        } else {
          showToast('取消收藏成功');
          const index = collectList.findIndex((item) => +item.news.id === +params.id);
          collectList.splice(index, 1);
          setCollectList([...collectList]);
        }
      } catch (_) {}
    }
  };
  return (
    <DetailWrapper>
      {info.body && <div dangerouslySetInnerHTML={{ __html: info.body }}></div>}
      <div className="action-box flex">
        <LeftOutline onClick={() => navigate(-1)} />
        <Badge content={extra.comments || 0} className="flex-center" style={{ '--right': '30%' }}>
          <MessageOutline />
        </Badge>
        <Badge content={extra.popularity || 0} className="flex-center" style={{ '--right': '30%' }}>
          <LikeOutline />
        </Badge>
        <StarOutline onClick={() => setCollection()} color={isCollection ? 'var(--adm-color-primary)' : ''} />
        <MoreOutline />
      </div>
    </DetailWrapper>
  );
});

export default connect((state) => state.base, null)(Detail);
